package com.junchao.peng.service.impl;

import com.junchao.peng.mapper.UserMapper;
import com.junchao.peng.pojo.User;
import com.junchao.peng.service.UserService;
import com.junchao.peng.utils.JsonResult;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author dell
 */
@Service("usersService")
public class UserServiceImpl implements UserService {
    final UserMapper userMapper;
    final JavaMailSenderImpl mailSender;
    final RedisTemplate redisTemplate;

    UserServiceImpl(UserMapper userMapper, RedisTemplate redisTemplate, JavaMailSenderImpl mailSender){
        this.mailSender = mailSender;
        this.redisTemplate = redisTemplate;
        this.userMapper = userMapper;
    }

    @Override
    public JsonResult sendVerificationCode(String email) {
        String i = (int) ((Math.random() * 9 + 1) * 100000) + "";
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("登录验证码");
        message.setText("验证码为：" + i );
        message.setTo(email);
        message.setFrom("2469478718@qq.com");
        mailSender.send(message);
        redisTemplate.opsForValue().set(email, i,5, TimeUnit.MINUTES);
        return new JsonResult("发送成功");
    }

    @Override
    public JsonResult confirm(String email, String code) {
        Object redisCode = redisTemplate.opsForValue().get(email);

        if (redisCode != null && redisCode.equals(code)){
            User user = userMapper.selectUserByEmail(email);
            setToken(email,user.getId() + "-" + code);
            return new JsonResult(Objects.requireNonNull(user).getId() + "-" + code);
        }
        return new JsonResult("验证码错误", 501);
    }

    @Override
    public JsonResult selectUserById(Integer id, String token) {
        if (getToken(token)){
            return new JsonResult("用户未登录",403);
        }
        User user = userMapper.selectUserById(id);
        if (user != null){
            return new JsonResult(user);
        }
        return new JsonResult("用户不存在",404);
    }

    @Override
    public JsonResult updateUser(User user, String token) {
        if (getToken(token)){
            return new JsonResult("用户未登录",403);
        }
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat(" yyyy-MM-dd HH:mm:ss " );
        String nowTime = sdf.format(date);
        Date time = null;
        try {
            time = sdf.parse(nowTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setUpdateTime(time);
        if (userMapper.updateUser(user)){
            return new JsonResult("修改成功");
        }
        return new JsonResult("修改失败请联系管理员",500);
    }

    @Override
    public JsonResult insertUser(User user) {
        int id = (int) ((Math.random() * 9 + 1) * 1000);
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat(" yyyy-MM-dd HH:mm:ss " );
        String nowTime = sdf.format(date);
        try {
            Date time = sdf.parse(nowTime);
            if (!userMapper.insertUser(user.getEmail(),user.getName(),user.getPhone(), time)){
                return new JsonResult("注册失败请联系管理员", 500);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new JsonResult("注册成功");
    }

    @Override
    public JsonResult deleteUser(Integer userId, String token) {
        String[] split = token.split("-");
        int i = Integer.parseInt(split[0]);
        User user = userMapper.selectUserById(i);
        if (getToken(token)){
            return new JsonResult("用户未登录",403);
        }
        if (user.getAdmin().equals(true)) {
            if (userMapper.deleteUser(userId)) {
                return new JsonResult("删除成功");
            }else {
                return new JsonResult("删除失败!");
            }
        }
        return new JsonResult("不是管理员!",403);
    }

    @Override
    public JsonResult listUser(String token) {
        if (getToken(token)){
            return new JsonResult("用户未登录",403);
        }
        return new JsonResult(userMapper.listUser());
    }

    private void setToken(String email, String token){
        redisTemplate.opsForValue().set(token, email,2, TimeUnit.HOURS);
    }

    private boolean getToken(String token){
        boolean flag = false;
        Object redisCode = redisTemplate.opsForValue().get(token);
        if (redisCode != null){
            flag = true;
        }
        return !flag;
    }
}
